<template>
  <div>
    <div class="control-container">
      <el-select
        v-model="targetIp"
        filterable
        allow-create
        default-first-option
        placeholder="请选择作用平台或者自定义ip"
        style="width: 300px; margin-right: 20px;"
      >
        <template #default>
          <el-option
            v-for="item in targetLocation"
            :key="item"
            :label="item"
            :value="item"
          >
            <span style="float:left">{{ item }}</span>
            <el-button
              v-if="item !== '开发服'"
              type="text"
              @click.stop="removeTargetLocation(item)"
              style="float:right;color:red;"
            >×</el-button>
          </el-option>
        </template>
      </el-select>
      <el-button @click="refresh" :loading="loading">刷新</el-button>
    </div>
    <div>开启/关闭GM：gm ai执行监听</div>
    <div>根据IP区分显示，仅能看到自己战斗的监听日志。仅可储存一场战斗的日志，开启下场战斗时会清空</div>
    <div v-if="data" class="data-display-container">
      <div class="data-header">
        <h3>AI执行日志</h3>
        <div class="time-info" v-if="data.time">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(data.time) }}</span>
        </div>
      </div>

      <div class="data-content">
        <!-- 新的嵌套列表结构 -->
        <div v-if="data.list && Array.isArray(data.list)" class="round-list">
          <div
            v-for="(roundData, roundIndex) in data.list"
            :key="roundIndex"
            class="round-item"
          >
            <!-- 回合标题和折叠控制 -->
            <div
              class="round-header"
              @click="toggleRound(roundIndex)"
            >
              <el-icon class="collapse-icon" :class="{ 'expanded': expandedRounds.includes(roundIndex) }">
                <ArrowRight />
              </el-icon>
              <span class="round-title">第 {{ roundData.round }} 回合</span>
            </div>

            <!-- 回合内容（可折叠） -->
            <div
              v-if="expandedRounds.includes(roundIndex)"
              class="round-content"
            >
              <div
                v-for="(unitData, unitIndex) in roundData.list"
                :key="unitIndex"
                class="unit-item"
              >
                <!-- 单位信息和折叠控制 -->
                <div
                  class="unit-header"
                  @click="toggleUnit(roundIndex, unitIndex)"
                >
                  <div class="unit-title-section">
                    <el-icon class="collapse-icon" :class="{ 'expanded': isUnitExpanded(roundIndex, unitIndex) }">
                      <ArrowRight />
                    </el-icon>
                    <span class="unit-name">unit名称:&nbsp;&nbsp;&nbsp;&nbsp;{{ unitData.name }}</span>
                  </div>
                  <div class="unit-ids">
                    <span>ai_id: {{ unitData.ai_id }}</span>
                    <span>base_id: {{ unitData.base_id }}</span>
                    <span>fid: {{ unitData.fid }}</span>
                  </div>
                </div>

                <!-- 执行列表（可折叠） -->
                <div
                  v-if="isUnitExpanded(roundIndex, unitIndex) && unitData.run_list && unitData.run_list.length > 0"
                  class="run-list"
                >
                  <div
                    v-for="(runItem, runIndex) in unitData.run_list"
                    :key="runIndex"
                    class="run-item"
                    :class="getLogItemClass(runItem)"
                  >
                    <span class="run-index">{{ runIndex + 1 }}</span>
                    <span class="run-content">{{ runItem }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 兼容旧格式 -->
        <div v-else-if="data.data && Array.isArray(data.data)" class="log-list">
          <div
            v-for="(logItem, index) in data.data"
            :key="index"
            class="log-item"
            :class="getLogItemClass(logItem)"
          >
            <span class="log-index">{{ index + 1 }}</span>
            <span class="log-content">{{ logItem }}</span>
          </div>
        </div>

        <!-- 原始数据展示 -->
        <div v-else class="raw-data">
          <h4>原始数据：</h4>
          <pre>{{ JSON.stringify(data, null, 2) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Clock, ArrowRight } from '@element-plus/icons-vue';
import type { Axios } from 'axios';

/**
 * 单位数据结构
 */
interface UnitData {
  ai_id: number;
  base_id: number;
  fid: number;
  name: string;
  run_list: string[];
}

/**
 * 回合数据结构
 */
interface RoundData {
  round: number;
  list: UnitData[];
}

/**
 * AI执行打印响应数据结构
 */
interface AiExecPrintResponse {
  list?: RoundData[];
  data?: string[];
  time?: number;
}

// 注入HTTP客户端
const http = inject<Axios>('http');

// 响应式数据
const loading = ref(false);
const data = ref<AiExecPrintResponse | null>(null);

// 目标IP和位置选择相关
const targetIp = ref<string>('开发服');
const targetLocation = ref<string[]>([
  '开发服',
  '开发服2'
]);

// 折叠控制
const expandedRounds = ref<number[]>([]);
const expandedUnits = ref<string[]>([]);

/**
 * 获取目标IP地址
 */
const getTargetIp = (): string => {
  switch (targetIp.value) {
    case '开发服':
      return '192.168.9.68:8127';
    case '开发服2':
      return '192.168.9.68:8128';
    default:
      return targetIp.value;
  }
};

/**
 * 保存targetIp和targetLocation到localStorage
 */
const saveTargetState = (): void => {
  localStorage.setItem('ai_exec_print_target_ip', targetIp.value);
  localStorage.setItem('ai_exec_print_target_location', JSON.stringify(targetLocation.value));
};

/**
 * 从localStorage加载targetIp和targetLocation
 */
const loadTargetState = (): void => {
  const savedIp = localStorage.getItem('ai_exec_print_target_ip');
  if (savedIp) {
    targetIp.value = savedIp;
  }

  const savedLocation = localStorage.getItem('ai_exec_print_target_location');
  if (savedLocation) {
    try {
      const locations = JSON.parse(savedLocation);
      if (Array.isArray(locations)) {
        targetLocation.value = locations;
      }
    } catch (error) {
      console.error('Error parsing saved target locations:', error);
    }
  }
};

/**
 * 删除目标位置选项
 */
const removeTargetLocation = (item: string): void => {
  // 不能删除当前正在选中的
  if (targetIp.value === item) {
    ElMessage.warning('请先切换到其他IP再删除');
    return;
  }
  const idx = targetLocation.value.indexOf(item);
  if (idx !== -1) {
    targetLocation.value.splice(idx, 1);
  }
};

/**
 * 格式化时间戳
 */
const formatTime = (timestamp: number | undefined): string => {
  if (!timestamp) return '';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

/**
 * 根据日志内容获取样式类
 */
const getLogItemClass = (logItem: string | undefined): string => {
  if (!logItem) return '';

  const item = logItem.toLowerCase();
  if (item.includes('执行规则') || item.includes('order:')) {
    return 'log-rule';
  } else if (item.includes('判断条件') || item.includes('条件类型')) {
    return 'log-condition';
  } else if (item.includes('进入') && item.includes('分支')) {
    return 'log-branch';
  } else if (item.includes('设定技能') || item.includes('目标:')) {
    return 'log-action';
  } else if (item.includes('条件结果: true')) {
    return 'log-success';
  } else if (item.includes('条件结果: false')) {
    return 'log-failure';
  }
  return 'log-default';
};

/**
 * 切换回合折叠状态
 */
const toggleRound = (roundIndex: number): void => {
  const index = expandedRounds.value.indexOf(roundIndex);
  if (index > -1) {
    expandedRounds.value.splice(index, 1);
  } else {
    expandedRounds.value.push(roundIndex);
  }
};

/**
 * 切换单位折叠状态
 */
const toggleUnit = (roundIndex: number, unitIndex: number): void => {
  const unitKey = `${roundIndex}-${unitIndex}`;
  const index = expandedUnits.value.indexOf(unitKey);
  if (index > -1) {
    expandedUnits.value.splice(index, 1);
  } else {
    expandedUnits.value.push(unitKey);
  }
};

/**
 * 检查单位是否展开
 */
const isUnitExpanded = (roundIndex: number, unitIndex: number): boolean => {
  const unitKey = `${roundIndex}-${unitIndex}`;
  return expandedUnits.value.includes(unitKey);
};

/**
 * 刷新数据 - 请求AI数据接口
 */
const refresh = async (): Promise<void> => {
  if (!http) {
    ElMessage.error('HTTP客户端未初始化');
    return;
  }

  loading.value = true;

  try {
    const targetUrl = `http://${getTargetIp()}/ai_print/req_ai_data`;
    const response = await http.get<AiExecPrintResponse>(targetUrl);
    data.value = response.data;
    ElMessage.success('数据获取成功');
  } catch (error: any) {
    console.error('请求失败:', error);
    ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 监听targetIp变化，自动加入targetLocation
watch(targetIp, () => {
  // 如果是新输入的IP，自动加入targetLocation
  if (targetIp.value && !targetLocation.value.includes(targetIp.value)) {
    targetLocation.value.push(targetIp.value);
  }
});

// 组件挂载时加载保存的状态
onMounted(() => {
  loadTargetState();
  // 添加页面刷新前的保存事件
  window.addEventListener('beforeunload', saveTargetState);
});
</script>

<style scoped>
.control-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.control-container .el-select {
  margin-right: 20px;
}

.control-container .el-button {
  margin-left: 0;
}

/* 数据展示容器样式 */
.data-display-container {
  margin-top: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.data-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.time-info {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.time-info .el-icon {
  margin-right: 4px;
}

.data-content {
  padding: 0;
}

/* 回合列表样式 */
.round-list {
  max-height: 600px;
  overflow-y: auto;
}

.round-item {
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  overflow: hidden;
}

.round-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #e4e7ed;
}

.round-header:hover {
  background: #f0f2f5;
}

.collapse-icon {
  margin-right: 8px;
  transition: transform 0.2s;
  color: #606266;
}

.collapse-icon.expanded {
  transform: rotate(90deg);
}

.round-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.round-content {
  padding: 0;
}

/* 单位项样式 */
.unit-item {
  border-bottom: 1px solid #f0f0f0;
}

.unit-item:last-child {
  border-bottom: none;
}

.unit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background: #fafbfc;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.unit-header:hover {
  background: #f0f2f5;
}

.unit-title-section {
  display: flex;
  align-items: center;
}

.unit-title-section .collapse-icon {
  margin-right: 8px;
  transition: transform 0.2s;
  color: #606266;
  font-size: 12px;
}

.unit-title-section .collapse-icon.expanded {
  transform: rotate(90deg);
}

.unit-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.unit-ids {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.unit-ids span {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 执行列表样式 */
.run-list {
  padding: 0;
}

.run-item {
  display: flex;
  padding: 8px 16px;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.run-item:hover {
  background-color: #f8f9fa;
}

.run-item:last-child {
  border-bottom: none;
}

.run-index {
  display: inline-block;
  min-width: 24px;
  padding: 2px 6px;
  margin-right: 12px;
  background: #e4e7ed;
  color: #606266;
  border-radius: 4px;
  font-size: 11px;
  text-align: center;
  font-weight: 500;
}

.run-content {
  flex: 1;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
  word-break: break-all;
}

/* 兼容旧格式的日志列表样式 */
.log-list {
  max-height: 600px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  padding: 8px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.log-item:hover {
  background-color: #f8f9fa;
}

.log-item:last-child {
  border-bottom: none;
}

.log-index {
  display: inline-block;
  min-width: 30px;
  padding: 2px 6px;
  margin-right: 12px;
  background: #e4e7ed;
  color: #606266;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  font-weight: 500;
}

.log-content {
  flex: 1;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  word-break: break-all;
}

/* 不同日志类型的样式 - 适用于 log-item 和 run-item */
.log-rule {
  background-color: #f0f9ff;
  border-left: 3px solid #409eff;
}

.log-rule .log-index,
.log-rule .run-index {
  background: #409eff;
  color: white;
}

.log-condition {
  background-color: #fff7e6;
  border-left: 3px solid #e6a23c;
}

.log-condition .log-index,
.log-condition .run-index {
  background: #e6a23c;
  color: white;
}

.log-branch {
  background-color: #f0f9ff;
  border-left: 3px solid #67c23a;
}

.log-branch .log-index,
.log-branch .run-index {
  background: #67c23a;
  color: white;
}

.log-action {
  background-color: #fdf6ec;
  border-left: 3px solid #f56c6c;
}

.log-action .log-index,
.log-action .run-index {
  background: #f56c6c;
  color: white;
}

.log-success {
  background-color: #f0f9ff;
  border-left: 3px solid #67c23a;
}

.log-success .log-index,
.log-success .run-index {
  background: #67c23a;
  color: white;
}

.log-success .log-content,
.log-success .run-content {
  color: #67c23a;
  font-weight: 500;
}

.log-failure {
  background-color: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.log-failure .log-index,
.log-failure .run-index {
  background: #f56c6c;
  color: white;
}

.log-failure .log-content,
.log-failure .run-content {
  color: #f56c6c;
  font-weight: 500;
}

.log-default {
  background-color: #f5f7fa;
  border-left: 3px solid #6965DB;
}

.log-default .log-index,
.log-default .run-index {
  background: #6965DB;
  color: white;
}


/* 原始数据样式 */
.raw-data {
  padding: 20px;
}

.raw-data h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.raw-data pre {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  overflow-x: auto;
  margin: 0;
}

/* 滚动条样式 */
.log-list::-webkit-scrollbar {
  width: 6px;
}

.log-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.log-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.log-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

